
import { _decorator, Component, Node, Prefab, instantiate } from 'cc';
import Loader from '../../Script/Common/Loader';
import yyComponent from '../../Script/Common/yyComponent';
import GlobalPool, { customPoolScript } from '../../Script/Common/GlobalPool';
const { ccclass, property } = _decorator;

@ccclass('ShopDisplay')
export class ShopDisplay extends yyComponent {
    //存放所有展示节点
    _allItems: { [type: number]: { [id: number]: Node } } = {};

    start() {
        Loader.loadBundle("Car", () => {
            Loader.loadBundleDir("Car", "Prefab/ui", (arr) => {
                for (let i = arr.length - 1; i >= 0; --i) {
                    GlobalPool.createPool(arr[i].data.name, arr[i], "ShopCar");
                }
            }, Prefab, false);
        }, false, false);
    }

    //切换展示物体
    display(type: number, id: number) {
        this.showCar(type, id);
    }

    protected carType: number = null;
    protected carId: number = null;
    protected curCarNode = null;
    protected removeCurCar() {
        if (!!this.curCarNode) {
            GlobalPool.put(this.curCarNode);
            this.curCarNode = null;
        }
    }
    protected showCar(type, id) {
        if (!!this.curCarNode && this.carId == id && this.carType == type) {
            return;
        }
        this.removeCurCar();
        this.carType = type;
        this.carId = id;
        let str = "ShopCar" + type + "_" + id;
        let node = GlobalPool.get(str);
        if (!!node) {
            this.addCar(node);
        } else {
            Loader.loadBundle("Car", () => {
                Loader.loadBundleRes("Car", "Prefab/ui/" + str, (res) => {
                    if (!res) {
                        return;
                    }
                    GlobalPool.createPool(str, res, "ShopCar");
                    if (this.carType == type && this.carId == id) {
                        let node2 = GlobalPool.get(str);
                        this.addCar(node2);
                    }
                });
            });
        }
    }
    protected addCar(node: Node) {
        if (!!this.curCarNode) {
            GlobalPool.put(this.curCarNode);
        }
        this.curCarNode = node;
        this.node.addChild(node);
        node[customPoolScript].show();
    }

}
